package eteam.aps.controller;

import cn.hutool.extra.qrcode.QrCodeUtil;
import cn.hutool.extra.qrcode.QrConfig;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import eteam.aps.api.U8Api;
import eteam.aps.client.CommonClient;
import eteam.aps.common.R;
import eteam.aps.common.exceptions.BusinessException;
import eteam.aps.common.helper.Helper;
import eteam.aps.systeminterface.model.vo.QueryInfoVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author LiuLei
 */
@RestController
@RequestMapping("/common")
@Api(tags = "公共模块")
public class CommonController {

    @Autowired
    private CommonClient commonClient;

    @PostMapping("/dict")
    @ApiOperation("根据名称获取字典信息")
    @ApiImplicitParam(name = "name", value = "字典名称")
    public R<List<String>> dictName(String name) throws Exception {
        R<List<QueryInfoVo>> r = commonClient.selectDdInfo(name);
        if (r.getCode() == 200) {
            return R.success(r.getData().stream().map(QueryInfoVo::getName).collect(Collectors.toList()));
        }
        throw new BusinessException(HttpStatus.BAD_REQUEST, r.getMsg());
    }

    @PostMapping("/rt")
    @ApiOperation("更新U8token")
    public R<String> resetU8token() throws Exception {
        return R.success(U8Api.resetU8token());
    }

    @PostMapping("/rs/{type}")
    @ApiOperation("获取收发类型")
    @ApiImplicitParam(name = "type", value = "收（1）/发（0）")
    public R<List<QueryInfoVo>> receiveOrSend(@PathVariable Integer type) throws Exception {
        return R.success(U8Api.getReceiveSendType(type));
    }

    @PostMapping("/pa/{type}")
    @ApiOperation("获取采购/销售类型")
    @ApiImplicitParam(name = "type", value = "【'cg'，采购】，【'xs'】，销售")
    public R<List<QueryInfoVo>> purOrSale(@PathVariable String type) throws Exception {
        if (Helper.isEmpty(type)) throw new BusinessException("类型不能为空！");
        return R.success(U8Api.getSaleOrPurType(type));
    }

    @GetMapping("qr")
    @ApiOperation("生成验证码")
    public void createQR(String code, HttpServletResponse response) throws IOException {
        QrConfig config = new QrConfig();
        config.setErrorCorrection(ErrorCorrectionLevel.H);
        String encode = URLEncoder.encode(code, "utf-8");
        byte[] bytes = QrCodeUtil.generatePng(encode, config);
        ServletOutputStream os = response.getOutputStream();
        os.write(bytes, 0, bytes.length);
    }

}
